<template>
	<view class="content">
		<view class="search-box">
			<u-search v-model="keyword" @change="inputChange" bg-color="#fff" :showAction="false"></u-search>

		</view>
		<view class="search-keyword">
			<scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y @scrolltolower="loadMore">
				<view class="listNull" v-if="keywordList.length==0">
					<img src="@/static/images/listNull.png" alt="" />
					<text>暂无商家</text>
				</view>
				<view v-for="(row,index) in keywordList" :key="index" @click="doDetail(row)">
					<view class="flex ">
						<view class="mr10 self-center">
							<u-image :src="row.logo" width="50" height="50"></u-image>
						</view>
						<view>
							<view style="font-weight: 700;">
								<u-parse :content="row.name"></u-parse>
							</view>
							<view style="font-size: 26rpx;" class="mt5">
								<u-parse :content="row.address"></u-parse>
							</view>
							<view class=" flex mt5" style="font-size: 26rpx;color: #909399;">
								<!-- <text class="mr10">云油价
									<text class="amount">
										<text class="symbol">￥</text>
										<text class="num">7.36
										</text>
										<text class="decimal">/L</text>
									</text>
								</text> -->
								<text style="font-family:SemiBold ;">距您{{(row.distance*1000).toFixed(2)}}.km</text>
							</view>
						</view>
					</view>
					<u-divider></u-divider>
				</view>
			</scroll-view>
			<!-- 分页控件 -->
			<!-- <u-pagination v-model="page" :page-count="pageCount" :total="pageTotal" mode="button" @change="pageChange" /> -->
			<scroll-view class="keyword-box" scroll-y>
				<view class="keyword-block">
					<view class="keyword-list-header">
						<view>历史搜索</view>
						<view>
							<u-icon name="trash-fill" size="18" @tap="oldDelete"></u-icon>
						</view>
					</view>
					<view class="keyword">
						<view v-for="(item,index) in oldKeywordList" @tap="doDetail(item)" :key="index">
							{{item.name}}
						</view>
					</view>

					<view v-if="!oldKeywordList.length" style="text-align: center;font-size: 26rpx;" class="mt10">暂无历史搜索
					</view>
				</view>

			</scroll-view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,computed
	} from 'vue';
	import API from "@/api/index.js"
	
	const keyword = ref('')
	const oldKeywordList = ref([])
	const keywordList = ref([])
	const isShowKeywordList = ref(false)
	let page = ref(1)
	let pageSize = ref(10)
	let pageTotal = ref(10)
	let loading = ref(false)
	let loadingState = ref('loadmore')
	// 计算总页数
	const pageCount = computed(() => {
		return Math.ceil(pageTotal.value / pageSize.value)
	})

	import {
		onLoad
	} from '@dcloudio/uni-app';

	onLoad(() => {
		init();
	})

	const init = () => {
		loadOldKeyword();
	}

	//加载历史搜索,自动读取本地Storage
	const loadOldKeyword = () => {
		uni.getStorage({
			key: 'oliOldKeys',
			success: (res) => {
				var OldKeys = JSON.parse(res.data);
				oldKeywordList.value = OldKeys;
			}
		});
	}

	const blur = () => {
		uni.hideKeyboard()
	}


	// 获取列表
	const getList = async (sData) => {
		keywordList.value = [];
		// // 处理中fileds中为null的数据
		// const filteredArray = fileds.filter(item => item !== null);
		try {
			loadingState.value = 'loading'
			let {
				data
			} = await API.list({
				"pageIndex": page.value,
				"pageSize": 10,
				"bySort":0,
				"earth": {
					"lat": uni.getStorageSync('location').lat,
					"lng": uni.getStorageSync('location').lng
				},
				"fileds": [
				// 	{
				// 	"filedIndex": "c",
				// 	// "filedValue": city.value ? city.value : uni.getStorageSync('location').city
				// },
				{
					"filedIndex": "name",
					"filedValue": keyword.value
				}]
			})
			console.log(data.list);
			// keywordList.value = drawCorrelativeKeyword([{
			// 		name: '周某啊啊啊啊',
			// 		address: '重庆市渝北',
			// 		id: 1
			// 	},
			// 	{
			// 		name: '李某啊啊啊啊',
			// 		address: '重庆市巴南',
			// 		id: 2
			// 	}
			// ], keyword);
			if (page.value == 1) {
				keywordList.value = drawCorrelativeKeyword(data.list, keyword);
			} else {
				keywordList.value =  drawCorrelativeKeyword([...keywordList.value, ...data.list], keyword)
			}
			pageTotal.value = data.total
			page.value = res.data.currentPage
			loadingState.value = keywordList.value.length >= pageTotal.value ? 'nomore' : 'loadmore'
		} catch (e) {
			loadingState.value = 'error'
		}
	}
	
	//监听输入
	const inputChange = (keyword) => {
		if (!keyword) {
			keywordList.value = [];
			isShowKeywordList.value = false;
			return;
		}
		isShowKeywordList.value = true;
		getList()
	}

	// 页码变化
	const pageChange = (page) => {
		page.value = page
		console.log("页码变化了", page.value);
		getList(page.value)
	}
	// 加载更多（滚动到底部）
	const loadMore = () => {
		console.log("滚动到底了");
		console.log(page.value, pageCount.value);
		if (page.value < pageCount.value) {
			page.value++
			setTimeout(() => {
				getList(page.value)
			}, 1000)
		}
	}
	//高亮关键字
	const drawCorrelativeKeyword = (keywords, keyword) => {
		return keywords.map(item => {
			item.name = item.name.replace(keyword, "<text style='color: #FF4110;font-weight:700'>" +
				keyword +
				"</text>");
			item.address = item.address.replace(keyword, "<text style='color: #FF4110;font-weight:700'>" +
				keyword +
				"</text>");
			return item
		})
	}

	//清除历史搜索
	const oldDelete = () => {
		uni.showModal({
			content: '确定清除历史搜索记录？',
			success: (res) => {
				if (res.confirm) {
					oldKeywordList.value = [];
					uni.removeStorage({
						key: 'oliOldKeys'
					});
				} else if (res.cancel) {}
			}
		});
	}
	//执行搜索
	const doDetail = (data) => {

		saveKeyword(data); //保存为历史 
		uni.redirectTo({
			// url: `/pages/gas_station_mall/gas_station_detail/index?id=1`
			url: '/pages/gas_station_mall/gas_station_detail/index?data=' + JSON
				.stringify(data)
		})

	}

	//保存关键字到历史记录
	const saveKeyword = (obj) => {
		uni.getStorage({
			key: 'oliOldKeys',
			success: (res) => {
				var OldKeys = JSON.parse(res.data);
				var findIndex = OldKeys.findIndex(item => item.name == obj.name)
				if (findIndex == -1) {
					OldKeys.unshift(obj);
				} else {
					OldKeys.splice(findIndex, 1);
					OldKeys.unshift(obj);
				}
				//最多10个纪录
				OldKeys.length > 10 && OldKeys.pop();
				uni.setStorage({
					key: 'oliOldKeys',
					data: JSON.stringify(OldKeys)
				});
				oldKeywordList.value = OldKeys; //更新历史搜索
			},
			fail: (e) => {
				var OldKeys = [obj];
				uni.setStorage({
					key: 'oliOldKeys',
					data: JSON.stringify(OldKeys)
				});
				oldKeywordList.value = OldKeys; //更新历史搜索
			}
		});
	}
</script>
<style lang="scss">
	.listNull {
		display: flex;
		flex-direction: column;
		text-align: center;
		margin: 0 auto;
	
		image {
			width: 200rpx;
			height: 200rpx;
			// margin: 10% 0 10% 10%;
			margin: 20rpx auto;
		}
	
		text {
			color: #919ea9;
		}
	}
	.search-box {
		width: 95%;
		background-color: rgb(242, 242, 242);
		padding: 15upx 2.5%;
		display: flex;
		justify-content: space-between;
		position: sticky;
		top: 0;
	}

	.search-box .mSearch-input-box {
		width: 100%;
	}

	.search-box .input-box {
		width: 85%;
		flex-shrink: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.search-box .search-btn {
		width: 15%;
		margin: 0 0 0 2%;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-shrink: 0;
		font-size: 28upx;
		color: #fff;
		background: linear-gradient(to right, #ff9801, #ff570a);
		border-radius: 60upx;
	}

	.search-box .input-box>input {
		width: 100%;
		height: 60upx;
		font-size: 32upx;
		border: 0;
		border-radius: 60upx;
		-webkit-appearance: none;
		-moz-appearance: none;
		appearance: none;
		padding: 0 3%;
		margin: 0;
		background-color: #ffffff;
	}

	.placeholder-class {
		color: #9e9e9e;
	}

	.search-keyword {
		width: 100%;
		background-color: rgb(242, 242, 242);
	}

	.keyword-list-box {
		height: calc(100vh - 110upx);
		padding: 20rpx;
		border-radius: 20upx 20upx 0 0;
		background-color: #fff;
	}

	.keyword-entry-tap {
		background-color: #eee;
	}

	.keyword-entry {
		width: 94%;
		height: 80upx;
		margin: 0 3%;
		font-size: 30upx;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: solid 1upx #e7e7e7;
	}

	.keyword-box {
		height: calc(100vh - 110upx);
		border-radius: 20upx 20upx 0 0;
		background-color: #fff;
	}

	.keyword-box .keyword-block {
		padding: 10upx 0;
	}

	.keyword-box .keyword-block .keyword-list-header {
		width: 94%;
		padding: 10upx 3%;
		font-size: 27upx;
		color: #333;
		display: flex;
		justify-content: space-between;
	}

	.keyword-box .keyword-block .keyword-list-header image {
		width: 40upx;
		height: 40upx;
	}

	.keyword-box .keyword-block .keyword {
		width: 94%;
		padding: 3px 3%;
		display: flex;
		flex-flow: wrap;
		justify-content: flex-start;
	}

	.keyword-box .keyword-block .hide-hot-tis {
		display: flex;
		justify-content: center;
		font-size: 28upx;
		color: #6b6b6b;
	}

	.keyword-box .keyword-block .keyword>view {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 60upx;
		padding: 0 20upx;
		margin: 10upx 20upx 10upx 0;
		height: 60upx;
		font-size: 28upx;
		background-color: rgb(242, 242, 242);
		color: #6b6b6b;
	}

	.amount {
		color: #e93323;
		font-family: SemiBold;
		font-weight: 700;
		font-family: "SemiBold";

		.symbol {
			font-size: 24rpx;
		}

		.num {
			font-size: 16px;
		}

		.decimal {
			font-size: 24rpx;
		}
	}
</style>